package com.document.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Sqls;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.Setup;

import com.document.dao.BasicDao;

public class DocSetup implements Setup{

	protected NutDao nutDao = null;
	
	/*
	 * public void setBasicDao(BasicDao basicDao) { this.basicDao = basicDao; }
	 */
	
	public void destroy(NutConfig config) {
		// TODO Auto-generated method stub
		
	}

	public void init(NutConfig config) {
		Ioc ioc = config.getIoc();
		nutDao = ioc.get(NutDao.class,"dao");
		Sql sql = Sqls.queryRecord("select t1.roleid,rolename,t3.resourcename,t3.url,t3.sn from b_role t1 "
				+ " left join b_resource_role t2 on t1.roleid=t2.roleid "
				+ " left join b_resource t3 on t2.resourceid=t3.resourceid order by t1.sn");
		sql.setCallback(new SqlCallbackImp());
		nutDao.execute(sql);
		HashMap rvtMap = (HashMap) sql.getResult();
		config.getServletContext().setAttribute("roleRight", rvtMap.get("roleRight"));
		config.getServletContext().setAttribute("roleList", rvtMap.get("roleList"));		
	}
	
	private class SqlCallbackImp implements SqlCallback {
		public Object invoke(Connection conn, ResultSet rs, Sql sql)
				throws SQLException {
			HashMap roleRight = new HashMap();
			List roleList = new ArrayList();
			HashMap map = null;
			List<Map> list = null;
			while (rs.next()) {
				map = new HashMap();
				map.put("roleid", "" + rs.getInt("roleid"));
				map.put("rolename", rs.getString("rolename"));
				map.put("resourcename", rs.getString("resourcename"));
				map.put("url", rs.getString("url"));
				map.put("sn", "" + rs.getInt("sn"));
				if (roleRight.containsKey(map.get("roleid"))) {
					list = (List) roleRight.get(map.get("roleid"));
					list.add(map);
				} else {
					list = new ArrayList();
					list.add(map);
					roleList.add(map);
				}
				roleRight.put(map.get("roleid"), list);
			}
			HashMap rvt = new HashMap();
			rvt.put("roleRight", roleRight);
			rvt.put("roleList", roleList);
			return rvt;
		}
	}
}
